// 698. 划分为k个相等的子集
// 去做减法
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */

// function 

var canPartitionKSubsets = function (nums, k) {
    // nums.sort((a, b) => a - b);
    const sum = nums.reduce((pre, cur) => (pre += cur), 0);
    let limit = Math.ceil(nums.length / k);
    let share = sum / k; // 每个集合的分数

    let result = [];

    console.log(sum, share, limit);

    for(let i = 0; i < k; i++) {
        let tempNums = [...nums];
        let dValue = share;
        let skipArr = [];

        while(dValue === 0) {
            let current = tempNums.pop();
            skipArr.push(tempNums.length);
            
            let temp = dValue - current;

            if (temp === 0) {
                nums = nums.filter((p, index) => !skipArr.includes(index));
                dValue = temp;
            }

            if (temp < 0) {
                tempNums.unshift(current);
                skipArr.pop();
                continue;   
            }

            let indexFind = tempNums.findIndex(p => p === temp);

            if (indexFind !== -1) {
                skipArr.push(indexFind);
                nums = nums.filter((p, index) => !skipArr.includes(index));
                break;
            }

            if (skipArr.length >= limit) {
                dValue = temp;
            }

        }
    }

    return true;
};

const nums = [4, 3, 2, 3, 5, 2, 1],
    k = 4;

console.log("1", canPartitionKSubsets(nums, k));
